package scc.com.httpssetting;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import scc.com.myapplication.R;

public class MainActivity extends AppCompatActivity {


    private OkHttpClient okHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initOkhttp();
    }

    private void initOkhttp() {
        okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(createSigleSSLSocketFactory())
//                 .hostnameVerifier(new TrustAllHostnameVerifier())
                .build();
    }

    /**
     * 王振  的证书 ： url4  server.cer client.bks
     * 王海章的证书：url2 server.crt  mymake.bks
     *
     * @param view
     * @throws IOException
     */

    public void click(View view) throws IOException {
        String url = "https://www.wanghaizhang.top/dcms/PwasAdmin/AreaKh-getCaseType.action";
        String url2 = "https://101.201.232.5/dcms/PwasAdmin/AreaKh-getCaseType.action";
        String url4 = "https://api.onezen.cc/v1/video/list";
        final Request request = new Request.Builder().url(url2).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("joker", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response)
                    throws IOException {
                String res = response.body().string();
                Log.e("joker", res);
            }
        });
    }

    private class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {


            return true;
        }
    }


    private SSLSocketFactory createSigleSSLSocketFactory() {
        try {
            InputStream inputStream = getAssets().open("server.crt");
            InputStream ksInputStream = getAssets().open("mymake.bks");
            TrustManager[] trustManagers = prepareTrustManager(new InputStream[]{inputStream});
            KeyManager[] keyManagers = prepareKeyManager(ksInputStream, "123456");
            SSLContext sslContext = SSLContext.getInstance("TLSv1.1");
            sslContext.init(keyManagers, trustManagers,
                    new SecureRandom());
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            return socketFactory;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 准备所信任的服务器证书
     *
     * @param certificates
     * @return
     */
    private TrustManager[] prepareTrustManager(InputStream... certificates) {
        if (certificates == null || certificates.length <= 0) {
            return null;
        }
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            String defaultType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            int index = 0;
            for (InputStream certificate : certificates) {
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
                try {
                    if (certificate != null) {
                        certificate.close();
                    }
                } catch (IOException e) {
                }
            }
            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            return trustManagers;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }


    /**
     * 准备服务器信任的客户端的证书
     *
     * @param bksFile
     * @param password
     * @return
     */
    private KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
        try {
            if (bksFile == null || password == null) {
                return null;
            }
            // Android默认的是BKS格式的证书
            KeyStore clientKeyStore = KeyStore.getInstance("BKS");
            clientKeyStore.load(bksFile, password.toCharArray());
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(clientKeyStore, password.toCharArray());
            return keyManagerFactory.getKeyManagers();

        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

//    private SSLSocketFactory createSSLSocketFactory() {
//        try {
//            SSLContext sslContext = SSLContext.getInstance("TLS");
//            // 服务器端需要验证的客户端证书
//            keyStore = KeyStore.getInstance(KEY_STORE_TYPE_P12);
//            // 客户端信任的服务器端证书
//            trustStore = KeyStore.getInstance(KEY_STORE_TYPE_BKS);
//
//
//            InputStream ksIn = getAssets().open("client.p12");
//            InputStream tsIn = getAssets().open("client.bks");
//
//
//            try {
//                keyStore.load(ksIn, "smallpay".toCharArray());
//                trustStore.load(tsIn, "smallpay".toCharArray());
//            } catch (Exception e) {
//                e.printStackTrace();
//            } finally {
//                try {
//                    ksIn.close();
//                } catch (Exception ignore) {
//                }
//                try {
//                    tsIn.close();
//                } catch (Exception ignore) {
//                }
//            }
//
//
//            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//            trustManagerFactory.init(trustStore);
//
//
//            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
//            keyManagerFactory.init(keyStore, "smallpay".toCharArray());
//
//            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
//                    new SecureRandom());
//
////            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
////            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
////                throw new IllegalStateException("Unexpected default trust managers:"
////                        + Arrays.toString(trustManagers));
////            }
////            X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
////
////            sslContext.init(keyManagerFactory.getKeyManagers(),new TrustManager[]{trustManager},
////                    new SecureRandom());
//
//
////            sslContext.init(null,new TrustManager[]{new X509TrustManager() {
////                @Override
////                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
////
////                }
////
////                @Override
////                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
////
////                }
////
////                @Override
////                public X509Certificate[] getAcceptedIssuers() {
////                    return new X509Certificate[0];
////                }
////            }},new SecureRandom());
//
//            SSLSocketFactory factory = sslContext.getSocketFactory();
//
//
//            return factory;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }